package com.badibadi.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.badibadi.logic.Util;
import com.badibadi.mytools.Utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

//数据接收错误
public class SocThread extends Thread {
	private String ip = "123.57.39.191";// 192.168.3.210   182.92.65.11
	private int port = 9876;// 9876
	// private String TAG = "socket thread";
	private int timeout = 3000;

	public Socket client = null;
	private PrintWriter out;
	private BufferedReader in;
	private InputStream inputStream;
	public boolean isRun = true;
	private Handler inHandler;
	private Handler outHandler;
	private Handler errHandler;
	private Context ctx;
	// private String TAG1 = "===Send===";
	private SharedPreferences sp;
	private boolean is_connect = false;
	private int temp_num = 0;

	/**
	 * 
	 * @param handlerin
	 *            接收
	 * @param handlerout
	 *            发送
	 * @param context
	 */
	public SocThread(Handler handlerin, Handler handlerout, Handler errhandler,
			Context context) {
		inHandler = handlerin;
		outHandler = handlerout;
		errHandler = errhandler;
		ctx = context;
//		   ("创建线程socket");
	}

	/**
	 * 连接socket服务器
	 */
	public void conn() {
		try {
			++temp_num;
			initdate();
//			   ("连接中。。。");
			client = new Socket(ip, port);
			client.setSoTimeout(timeout);// 设置阻塞时间
//			   ("连接成功");
			in = new BufferedReader(new InputStreamReader(
					client.getInputStream(), "GBK"));
			inputStream = client.getInputStream();
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
					client.getOutputStream(), "gb2312")), true);
//			   ("输入输出流获取成功");
			// Put_ORR("网络聊天连接成功");
		} catch (UnknownHostException e) {
			//    ("连接错误UnknownHostException 重新获取");
			   
			// close();
			if (temp_num < 5) {
				conn();
			}else{
				Send_Geshi_Tool.stopSocket();
			}
			// Put_ORR("网络聊天连接错误,重新获取");
		} catch (IOException e) {
//			   ("连接服务器io错误");
			// Put_ORR("连接服务器失败,请稍后再试!");
			Send_Geshi_Tool.stopSocket();
			// errHandler.sendEmptyMessageDelayed(2, 5000);
			// close();
			// conn();
			   
		} catch (Exception e) {
//			   ("连接服务器错误Exception" + e.getMessage());
			Send_Geshi_Tool.stopSocket();
			// errHandler.sendEmptyMessageDelayed(2, 5000);
			// Put_ORR("网络聊天连接失败,与服务器断开连接");
			   
		}
	}

	private void Put_ORR(String s) {
		// String s = "网络聊天连接失败,与服务器断开连接";
		Message message = new Message();
		Bundle bundle = new Bundle();
		message.what = 1;
		bundle.putString("result", s);
		message.setData(bundle);
		errHandler.sendMessage(message);
	}

	public void initdate() {
		sp = ctx.getSharedPreferences("SP", ctx.MODE_PRIVATE);
		ip = sp.getString("ipstr", ip);
		port = Integer.parseInt(sp.getString("port", String.valueOf(port)));
		//    ("获取到ip端口:" + ip + ";" + port);
	}

	/**
	 * 实时接受数据
	 */
	@Override
	public void run() {
		conn();
		String line = "";
		while (isRun) {
			try {
				if (client != null) {
					char[] s1 = new char[1024];

					int qi = in.read(s1, 0, s1.length);
					if (qi != 0) {
						try {
							line = String.valueOf(s1);
						} catch (Exception e) {
							// TODO: handle exception
							line="";
						}
					
						Message msg = inHandler.obtainMessage();
						msg.obj = line;
						inHandler.sendMessage(msg);// 结果返回给UI处理
						// Message mes = new Message();
						// Bundle bun = new Bundle();
						// mes.what = 1;
						// bun.putString("result", line);
						// mes.setData(bun);
						// inHandler.sendMessage(mes);
						qi = 0;
					}
				} else {
					//    ("没有可用连接");
					conn();
				}
			} catch (Exception e) {
				// Utils.print6(Utils.path, "数据接收错误" + e.getMessage());
				Send_Geshi_Tool.stopSocket();
				// errHandler.sendEmptyMessageDelayed(2, 5000);
				//    ("数据接收错误" + e.getMessage());
				   
			}
		}
	}

	/**
	 * 发送数据
	 * 
	 * @param mess
	 */
	public void Send(String mess) {
		try {
			if (client != null) {
				out.println(mess);
				out.flush();
				Message msg = outHandler.obtainMessage();
				msg.obj = mess;
				msg.what = 1;
				outHandler.sendMessage(msg);// 结果返回给UI处理
			} else {
//				   ("client 不存在");
				Message msg = outHandler.obtainMessage();
				msg.obj = mess;
				msg.what = 0;
				outHandler.sendMessage(msg);// 结果返回给UI处理
				conn();
			}

		} catch (Exception e) {
			   
		} finally {
		}
	}

	/**
	 * 关闭连接
	 */
	public void close() {
		try {
			if (client != null) {
				in.close();
				out.close();
				inputStream.close();
				client.close();
			}
		} catch (Exception e) {
			   
		}

	}
}
